/**
 * V3认证服务 - 简化公共JavaScript库
 */

// 简化的通知系统
function showNotification(message, type = 'info', duration = 3000) {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '8px',
        color: 'white',
        fontSize: '14px',
        fontWeight: '500',
        zIndex: '1000',
        maxWidth: '300px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        transition: 'all 0.3s ease',
        transform: 'translateX(100%)',
        opacity: '0'
    });
    
    // 根据类型设置背景色
    const colors = {
        success: '#28a745',
        error: '#dc3545', 
        warning: '#ffc107',
        info: '#007bff'
    };
    notification.style.background = colors[type] || colors.info;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
        notification.style.opacity = '1';
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        notification.style.opacity = '0';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, duration);
}

// 简化的表单验证
function validateForm(form) {
    const inputs = form.querySelectorAll('[required]');
    let isValid = true;
    
    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.style.borderColor = '#dc3545';
            isValid = false;
        } else {
            input.style.borderColor = '';
        }
    });
    
    if (!isValid) {
        showNotification('请填写所有必填字段', 'error');
    }
    
    return isValid;
}

// 简化的API请求
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`请求失败: ${response.status}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return await response.json();
        } else {
            return await response.text();
        }
    } catch (error) {
        showNotification(error.message, 'error');
        throw error;
    }
}

// OAuth2工具函数
const OAuth2Utils = {
    // 构建授权URL
    buildAuthUrl(params = {}) {
        const defaultParams = {
            response_type: 'code',
            client_id: 'v3-client',
            redirect_uri: window.location.origin + '/oauth2/callback',
            scope: 'read write',
            state: this.generateState()
        };
        
        const finalParams = { ...defaultParams, ...params };
        const searchParams = new URLSearchParams(finalParams);
        
        return `/oauth2/authorize?${searchParams.toString()}`;
    },
    
    // 生成状态码
    generateState() {
        return Math.random().toString(36).substring(2, 15);
    },
    
    // 存储参数
    storeParams(params) {
        localStorage.setItem('oauth2_params', JSON.stringify(params));
    },
    
    // 获取参数
    getParams() {
        const stored = localStorage.getItem('oauth2_params');
        return stored ? JSON.parse(stored) : null;
    },
    
    // 清除参数
    clearParams() {
        localStorage.removeItem('oauth2_params');
    },
    
    // 交换令牌
    async exchangeToken(authCode, clientId, clientSecret, redirectUri) {
        const tokenData = new URLSearchParams({
            grant_type: 'authorization_code',
            code: authCode,
            client_id: clientId,
            client_secret: clientSecret,
            redirect_uri: redirectUri
        });

        try {
            const response = await apiRequest('/oauth2/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: tokenData
            });

            showNotification('令牌交换成功', 'success');
            return response;
        } catch (error) {
            showNotification('令牌交换失败', 'error');
            throw error;
        }
    }
};

// 工具函数
const Utils = {
    // 防抖
    debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    },
    
    // 节流
    throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // 格式化时间
    formatTime(date = new Date()) {
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    },
    
    // 生成随机字符串
    randomString(length = 8) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }
};

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    // 为所有表单添加验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
            }
        });
    });
    
    // 清除输入框错误状态
    const inputs = document.querySelectorAll('input, textarea');
    inputs.forEach(input => {
        input.addEventListener('input', function() {
            this.style.borderColor = '';
        });
    });
});

// 全局暴露
window.showNotification = showNotification;
window.validateForm = validateForm;
window.apiRequest = apiRequest;
window.OAuth2Utils = OAuth2Utils;
window.Utils = Utils; 